package com.qdxwx.manage.controller.course;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.ImageUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.course.CourseFileService;
import com.qdxwx.data.service.course.CourseNodeService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.course.CourseTeacherService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.course.CourseNode;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.enums.CourseType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.teacher.Teacher;
import com.qdxwx.models.teacher.TeacherQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/course")
public class CourseEditController extends BaseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseNodeService courseNodeService;
    @Autowired
    private CourseTeacherService courseTeacherService;
    @Autowired
    private CourseFileService courseFileService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private WebsiteProfileService websiteProfileService;

    /**
     * 新增课程
     */
    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if(manager == null) return error404;
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if(channelId < 1) return error404;
        Course course = new Course();
        course.setChannelId(channelId);
        course.setCourseId(0);
        course.setPrice(0);
        course.setSourcePrice(0);
        course.setSellType(CourseType.COURSE.toString());
        Teacher teacher = teacherService.getByMobile(manager.getMobile());
        List<Integer> teacherIds = new ArrayList<>();
        if (teacher!=null){
            teacherIds.add(teacher.getId());
        }
        mmap.put("course", course);
        mmap.put("teacherIds", teacherIds);
        TeacherQuery teacherQuery =  new TeacherQuery();
        teacherQuery.setIsDisabled(0);
        List<Teacher> teacherList = teacherService.getList(teacherQuery, null);
        mmap.put("teacherList", teacherList);
        return "course/course-edit";
    }


    /**
     * 修改课程
     */
    @GetMapping("/edit.html")
    @Permissions("course:edit")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        int courseId = TKConvert.toInteger(request.getParameter("id"));
        if (courseId < 1) return error404;
        Course course = courseService.get(courseId);
        if (course == null) return error500;
        List<Integer> teacherIds = courseTeacherService.getTeacherIds(courseId);
        TeacherQuery teacherQuery =  new TeacherQuery();
        teacherQuery.setIsDisabled(0);
        List<Teacher> teacherList = teacherService.getList(teacherQuery, null);
        mmap.put("course", course);
        mmap.put("teacherIds", teacherIds);
        mmap.put("teacherList", teacherList);
        return "course/course-edit";
    }

    /**
     * 保存课程
     */
    @PostMapping("/save.json")
    @Permissions("course:edit")
    @Log(title = "编辑课程", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult saveCourse(HttpServletRequest request) {
        int courseId = TKConvert.toInteger(request.getParameter("courseId"));
        Course course = new Course();
        if (courseId > 0) {
            course = courseService.get(courseId);
            if (course == null){
                return error("找不到id为:" + courseId + "的课程");
            }
        }
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return error("请选择所属分类！");
        Category category = categoryService.get(categoryId);
        if (category == null) return error("找不到指定分类信息");

        String courseName = request.getParameter("courseName");
        if (TKString.isEmpty(courseName)) return error("标题不能为空");
        String badWord = websiteProfileService.checkBadWord(courseName);
        if (badWord != null) {
            return error("课程标题含有敏感词‘" + badWord + "’，请删除后重新提交！");
        }
        String sellType = request.getParameter("sellType");
        if (TKString.isEmpty(sellType)) return error("请选择类型");
        String teacherIds = request.getParameter("teacherIdArr");
        if (TKString.isEmpty(teacherIds)) return error("请至少选择一名教师");
        String intro = request.getParameter("intro");
        badWord = websiteProfileService.checkBadWord(intro);
        if (badWord != null) {
            return error("课程简介含有敏感词‘" + badWord + "’，请删除后重新提交！");
        }
        String cover = request.getParameter("cover");
        if (TKString.isEmpty(cover)) return error("请上传封面图片");
        String context = request.getParameter("context");
        if (TKString.isEmpty(context)) return error("请输入课程详情");
        badWord = websiteProfileService.checkBadWord(context);
        if (badWord!=null) {
            return error("课程详情含有敏感词‘" + badWord + "’，请删除后重新提交！");
        }
        course.setCourseName(courseName);
        course.setCategoryId(category.getCategoryId());
        course.setCategoryName(category.getCategoryName());
        course.setChannelId(category.getChannelId());
        course.setSubjectId(category.getSubjectId());
        course.setSellType(sellType);
        if ("LIVE".equals(sellType)) {
            course.setLiveBeginTime(TKConvert.toLocalDateTime(request.getParameter("liveBeginTime")));
            course.setLiveEndTime(TKConvert.toLocalDateTime(request.getParameter("liveEndTime")));
        }
        course.setLessonNum(TKConvert.toInteger(request.getParameter("lessonNum")));
        course.setExpireDate(LocalDate.now().plusDays(730));
        course.setSourcePrice(TKConvert.toBigDecimal(request.getParameter("sourcePrice")).multiply(BigDecimal.valueOf(100)).intValue());
        course.setPrice(TKConvert.toBigDecimal(request.getParameter("price")).multiply(BigDecimal.valueOf(100)).intValue());
        course.setIntro(intro);
        course.setCover(cover);
        course.setContext(context);
        course.setUserId(TKConvert.toLong(request.getParameter("userId")));
        course.setIsElite(TKConvert.toInteger(request.getParameter("isElite"),0));
        course.setIsTop(TKConvert.toInteger(request.getParameter("isTop"),0));
        course.setBuyCount(TKConvert.toInteger(request.getParameter("buyCount"),0));
        course.setViewCount(TKConvert.toInteger(request.getParameter("viewCount"),0));
        course.setBookId(TKConvert.toInteger(request.getParameter("bookId")));
        //封面裁剪
        if(!TKString.isEmpty(course.getCover())) {
            int w = 400;
            int h = 280;
            if(course.getChannelId() == 2 || TKConvert.toInteger(request.getParameter("channelId")) == 2){
                w = 300;
                h = 390;
            }
            String oldPath = course.getCover();
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadCoverThumb, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                logger.info("oldPath:" + oldPath);
                logger.info("newPath:" + newPath);
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, w, h);
                course.setCover(newPath);
            }
        }
        int row;
        if (courseId > 0) {
            row = courseService.update(course);
        } else {
            course.setIsAvailable(0);
            row = courseService.insert(course);
        }
        if (row > 0) {
            courseTeacherService.deleteByCourseId(course.getCourseId());
            courseTeacherService.insert(course.getCourseId(), TKConvert.toIntList(teacherIds));
        }
        return toAjax(row);
    }


    /**
     * 修改保存课程
     */
    @PostMapping("/update/available.json")
    @Permissions("course:edit")
    @Log(title = "修改课程状态", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult UpdateIsAvailable(HttpServletRequest request) {
        int courseId = TKConvert.toInteger(request.getParameter("id"));
        int isAvailable = TKConvert.toInteger(request.getParameter("isAvailable"));
        if (courseId < 1) return error("参数异常");
        Course course = courseService.get(courseId);
        if (course == null) return error("找不到courseId为:" + courseId + "的课程");
        if (isAvailable == 1) {
            if (course.getSellType().equals("PACKAGE")) {
                Course queryCourse = new Course();
                queryCourse.setCourseId(course.getCourseId());
                long count = courseService.getPackageCount(queryCourse);
                if (count < 1) return error("套餐内无上架课程,暂不能上架");
            } else {
                CourseNode courseNode = new CourseNode();
                courseNode.setCourseId(course.getCourseId());
                courseNode.setNodeType(1);
                long count = courseNodeService.count(courseNode);
                if (count < 1) return error("课程内无任何章节,暂不能上架");
            }
        }
        course.setIsAvailable(isAvailable);
        return toAjax(courseService.update(course));
    }

    /**
     * 删除课程
     */
    @Permissions("course:remove")
    @Log(title = "删除课程", businessType = BusinessType.DELETE)
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("ids"));
        if(id < 1) return error("参数异常");
        Course course = courseService.get(id);
        if(course == null) return error("找不到指定课程");
        if(course.getIsAvailable() == 1) return error("上架课程不能删除");
        CourseNode courseNode = new CourseNode();
        courseNode.setCourseId(id);
        long count = courseNodeService.count(courseNode);
        if(count > 0) return error("请先删除课程内的所有章节");
        courseTeacherService.deleteByCourseId(id);//同时删除关联表
        courseFileService.deleteByCourseId(id);//同时删除相关文件
        return toAjax(courseService.delete(id));
    }

    //课程详情
    @GetMapping("/view.html")
    public String courseInfo(HttpServletRequest request, ModelMap mmap) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if(id < 1) return error404;
        Course course = courseService.get(id);
        if(course == null) return error404;
        Category category = categoryService.get(course.getCategoryId());
        List<Teacher> teacherList = teacherService.getListByCourseId(course.getCourseId());
        mmap.put("channel", channelService.get(course.getChannelId()));
        mmap.put("category", category);
        mmap.put("teacherList", teacherList);
        mmap.put("course", course);
        mmap.put("manager", SessionUtils.getManager());
        return "course/course-view";
    }

    //置顶操作
    @PostMapping("/top/clicked.json")
    @ResponseBody
    @Permissions("course:edit")
    public AjaxResult isTopClicked(HttpServletRequest request) {
        int courseId = TKConvert.toInteger(request.getParameter("courseId"));
        int isTop = TKConvert.toInteger(request.getParameter("isTop"));
        if (courseId < 1) return error("参数异常");
        Course course = courseService.get(courseId);
        if (course == null) return error("找不到指定课程");
        course.setIsTop(isTop > 0 ? 1 : 0);
        return toAjax(courseService.update(course));
    }

    //推荐操作
    @PostMapping("/elite/clicked.json")
    @ResponseBody
    @Permissions("course:edit")
    public AjaxResult isEliteClicked(HttpServletRequest request) {
        int courseId = TKConvert.toInteger(request.getParameter("courseId"));
        int isElite = TKConvert.toInteger(request.getParameter("isElite"));
        if (courseId < 1) return error("参数异常");
        Course course = courseService.get(courseId);
        if (course == null) return error("找不到指定课程");
        course.setIsElite(isElite > 0 ? 1 : 0);
        return toAjax(courseService.update(course));
    }

}
